package cn.datax.service.data.market.service.impl;

import cn.datax.common.base.BaseServiceImpl;
import cn.datax.common.core.DataConstant;
import cn.datax.common.core.RedisConstant;
import cn.datax.common.exception.DataException;
import cn.datax.common.rabbitmq.config.RabbitMqConstant;
import cn.datax.common.redis.service.RedisService;
import cn.datax.common.utils.MD5Util;
import cn.datax.common.utils.MsgFormatUtil;
import cn.datax.common.utils.SecurityUtil;
import cn.datax.service.data.market.cata.dto.UserResourceInfoDto;
import cn.datax.service.data.market.cata.entity.UserResourceInfoEntity;
import cn.datax.service.data.market.dao.UserResourceInfoDao;
import cn.datax.service.data.market.mapstruct.UserResourceInfoMapper;
import cn.datax.service.data.market.service.UserResourceService;
import cn.datax.service.workflow.api.dto.ProcessInstanceCreateRequest;
import cn.datax.service.workflow.api.entity.BusinessEntity;
import cn.datax.service.workflow.api.feign.FlowInstanceServiceFeign;
import cn.datax.service.workflow.api.vo.FlowInstanceVo;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 用户资源关系信息表 服务实现类
 * </p>
 *
 * @author yuwei
 * @since 2020-03-31
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserResourceServiceImpl extends BaseServiceImpl<UserResourceInfoDao, UserResourceInfoEntity> implements UserResourceService {

    private static String DEFAULT_BUSINESS_CODE = "6020";

    @Autowired
    private UserResourceInfoMapper userResourceInfoMapper;

    @Autowired
    private RedisService redisService;
    
    @Autowired
    private  UserResourceInfoDao userResourceDao;

    @Autowired
    private FlowInstanceServiceFeign flowInstanceServiceFeign;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserResourceInfoEntity saveData(UserResourceInfoDto dataDto) {
        UserResourceInfoEntity entity = userResourceInfoMapper.toEntity(dataDto);
        userResourceDao.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateData(UserResourceInfoDto dataDto) {
        UserResourceInfoEntity dataApi = userResourceInfoMapper.toEntity(dataDto);
        userResourceDao.updateById(dataApi);
    }

    @Override
    public List<UserResourceInfoEntity> getUserResourceByUserId(String userId, String resourcrType) {
        Map param = new HashMap();
        if(null == userId || userId.isEmpty()){
            userId = SecurityUtil.getUserId();
        }
        param.put("user_id",userId);
        param.put("resource_type",resourcrType);
        List<UserResourceInfoEntity> list = null;
        if("api".equals(resourcrType)){
            list = userResourceDao.listUserApiResourceInfoByMap(param);
        }else if("api".equals(resourcrType)){
            list = userResourceDao.listUserTableResourceInfoByMap(param);
        }
        return list;
    }
    @Override
    public IPage<UserResourceInfoEntity> pageGetUserResourceByUserId(Page page, String userId, String resourceType,String resourceName) {
        System.out.println("########################pageGetUserResourceByUserId" + resourceType);
        IPage<UserResourceInfoEntity> iPage = new Page<>(page.getCurrent(), page.getSize());
        Map param = new HashMap();
        if(null == userId || userId.isEmpty()){
            userId = SecurityUtil.getUserId();
        }
        param.put("userId",userId);
        param.put("resourceType",resourceType);
        if(null != resourceName){
            param.put("resource_name",resourceName);
        }
        IPage<UserResourceInfoEntity> list = null;
        if("api".equals(resourceType)){
            list = userResourceDao.pageUserApiResourceInfoByMap(iPage,param);
        }else if("table".equals(resourceType)){
            list = userResourceDao.pageUserTableResourceInfoByMap(iPage,param);
        }else { // 没传递参数 认为查询全部数据
            list = userResourceDao.pageAllUserResourceInfoByMap(iPage,param);
        }
        return list;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataById(String id) {
        userResourceDao.deleteById(id);
    }

    /**
     * 提交资源申请
     * @param id
     */
    @Override
    public void applySubmit(String id) {
        BusinessEntity businessEntity = (BusinessEntity) redisService.hget(RedisConstant.WORKFLOW_BUSINESS_KEY, DEFAULT_BUSINESS_CODE);
        if (businessEntity != null) {
            ProcessInstanceCreateRequest request = new ProcessInstanceCreateRequest();
            request.setSubmitter(SecurityUtil.getUserId());
            request.setBusinessKey(id);
            request.setBusinessCode(DEFAULT_BUSINESS_CODE);
            request.setBusinessAuditGroup(businessEntity.getBusinessAuditGroup());
            String processDefinitionId = businessEntity.getProcessDefinitionId();
            request.setProcessDefinitionId(processDefinitionId);
            // 流程实例标题(动态拼接)
            String tempalte = businessEntity.getBusinessTempalte();
            String businessName = businessEntity.getBusinessName();
            Map<String, String> parameters = new HashMap<>(4);
            parameters.put(MsgFormatUtil.TEMPALTE_NICKNAME, SecurityUtil.getNickname());
            parameters.put(MsgFormatUtil.TEMPALTE_DATETIME, DateUtil.formatLocalDateTime(LocalDateTime.now()));
            parameters.put(MsgFormatUtil.TEMPALTE_BUSINESS_NAME, businessName);
            parameters.put(MsgFormatUtil.TEMPALTE_BUSINESS_KEY, id);
            String content = MsgFormatUtil.getContent(tempalte, parameters);
            request.setBusinessName(content);
            FlowInstanceVo flowInstanceVo = flowInstanceServiceFeign.startById(request);
            if (flowInstanceVo != null) {
                UserResourceInfoEntity UserResourceInfoEntity = new UserResourceInfoEntity();
                UserResourceInfoEntity.setId(id);
                UserResourceInfoEntity.setProcessInstanceId(flowInstanceVo.getProcessInstanceId());
                userResourceDao.updateById(UserResourceInfoEntity);
            }
        } else {
            throw new DataException("业务流程未配置");
        }
    }
}
